import { fromHTML, waitFor } from '../../../common';

export type ButtonElement = Brand<HTMLElement, 'button'>;

let navEl: HTMLElement | null = null;

export function createButtonElement(text: string, icon: string): ButtonElement {
	return fromHTML(`
		<div class="navigation__native-cta ame-sidebar-button">
			<div slot="native-cta">
				<div data-testid="native-cta" class="native-cta">
					<button class="native-cta__button" data-testid="native-cta-button">
						<span class="native-cta__app-icon">
							${icon}
						</span>
						<span class="native-cta__label">${text}</span>
					</button>
				</div>
			</div>
		</div>
    `) as ButtonElement;
}

export async function showButtonElement(buttonEl: ButtonElement, index: number) {
	if (!navEl) {
		navEl = await waitFor('nav', 'amp-chrome-player');
		if (!navEl) return;
	}

	const buttonEls = Array.from(navEl.querySelectorAll('.ame-sidebar-button')) as HTMLElement[];
	buttonEl.setAttribute('data-index', index.toString());

	if (buttonEls.length === 0) {
		navEl.append(buttonEl);
		return;
	}

	let bestDist = Number.MAX_VALUE;
	let refEl = buttonEls[0];

	for (const buttonEl of buttonEls) {
		const dist = Math.abs(Number(buttonEl.getAttribute('data-index')) - index);
		if (dist >= bestDist) continue;

		bestDist = dist;
		refEl = buttonEl;
	}

	if (index > Number(refEl.getAttribute('data-index'))) {
		refEl.after(buttonEl);
	} else {
		refEl.before(buttonEl);
	}
}

export async function hideButtonElement(buttonEl: ButtonElement) {
	buttonEl.remove();
}
